package com.gufe.service.user.impl.mp.message;

import com.gufe.dto.message.MsgListDTO;
import com.gufe.entity.MsgAndUser;
import com.gufe.exception.NullDataException;
import com.gufe.mapper.user.message.MessageMapper;
import com.gufe.service.user.message.MessageService;
import com.gufe.vo.message.MsgListVO;
import com.gufe.vo.message.MsgUserListVO;
import com.gufe.vo.message.MsgUserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class MessageServiceImpl implements MessageService {

    @Autowired
    MessageMapper messageMapper;

    //存储单条消息
    @Override
    @Transactional
    public boolean insertMsg(Long fromUserId, Long toUserId, String msgContent) {
        //先查询二者是否聊过天（是否互为好友）
        Long selfRelationId = messageMapper.getFriendExist(fromUserId, toUserId);
        Long objectRelationId = messageMapper.getFriendExist(toUserId, fromUserId);
        if (objectRelationId == null || selfRelationId == null) {
            return false;
        }
        //是好友关系，开始同步两条数据
        //1.自己方的数据，状态为已读，自己方未读数量不变
        messageMapper.insertMsg(selfRelationId, msgContent, 1);

        //2.对方的数据，总未读数量加一
        //添加未读消息数
        messageMapper.addUnReadCount(objectRelationId);

        //设置为双方最后一条聊天记录
        messageMapper.updateLastMsg(selfRelationId, msgContent);
        messageMapper.updateLastMsg(objectRelationId, msgContent);
        return true;
    }

    //获取详细聊天记录
    @Override
    @Transactional
    public List<MsgListVO> getMsgList(MsgListDTO msgListDTO) {
        if (msgListDTO.getUserId() == null || msgListDTO.getChatId() == null) {
            throw new NullDataException("获取聊天记录失败，发送方id或接收方id为空！");
        }
        //获取聊天记录，多表查询
        List<MsgListVO> listVOS = messageMapper.getMsgList(msgListDTO.getUserId(), msgListDTO.getChatId());
        //清除自己的未读数
        messageMapper.cleanUnReadCount(msgListDTO.getUserId(), msgListDTO.getChatId());
        return listVOS;
    }



    //获取聊天消息列表信息
    @Override
    public MsgUserListVO getMsgUserList(Long userId) {
        List<MsgAndUser> msgAndUserList = messageMapper.getMsgUserList(userId);
        List<MsgUserVO> listVOS = new ArrayList<>();
        int unreadCount = 0;
        for (MsgAndUser msgAndUser : msgAndUserList) {
            MsgUserVO vo = new MsgUserVO();
            vo.setAvatar(msgAndUser.getReceiverAvatar());
            vo.setLastMsg(msgAndUser.getLastMsg());
            vo.setName(msgAndUser.getReceiverNickname());
            vo.setReceiverId(msgAndUser.getReceiverId());
            vo.setUnread(msgAndUser.getUnreadCount());
            vo.setTime(formatTime(msgAndUser.getUpdatedAt()));
            vo.setOnline(msgAndUser.getReceiverOnlineStatus());
            unreadCount += msgAndUser.getUnreadCount();
            listVOS.add(vo);
        }
        return new MsgUserListVO(unreadCount, listVOS);
    }

    //设置用户在线
    @Override
    public void setOnlieStatus(Long userId,int i) {
        messageMapper.setOnlineStatus(userId,i);
    }

    //清除未读消息
    @Override
    public void cleanUnread(Long userId, Long receiverId) {
        messageMapper.cleanUnReadCount(userId,receiverId);
    }

    public static String formatTime(LocalDateTime time) {
        // 获取当前日期和时间
        LocalDateTime now = LocalDateTime.now();
        LocalDate today = now.toLocalDate();
        LocalDate yesterday = today.minusDays(1);

        // 获取传入时间的日期部分
        LocalDate timeDate = time.toLocalDate();

        // 定义时间格式化器
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-M-d HH:mm");

        // 判断是否是今天
        if (timeDate.equals(today)) {
            return time.format(timeFormatter); // 只显示时间，如 17:25
        }
        // 判断是否是昨天
        else if (timeDate.equals(yesterday)) {
            return "昨天 " + time.format(timeFormatter); // 显示为：昨天 17:25
        }
        // 如果是昨天以前
        else {
            return time.format(dateTimeFormatter); // 显示为：2025-3-12 17:25
        }
    }


}
